<template>
  <div class="app-container">
    <div v-if="editorVisible" class="wf-edior">

      <el-dialog
        class="fieldIndex"
        :title="dialogTitle"
        :visible.sync="editorVisible"
        fullscreen
        close-on-press-escape
        :before-close="closeAndSave"
      >
        <design :title="dialogTitle" ref="designData" :formJson="formJson" :moduleFormId="moduleFormId"/>
      </el-dialog>
    </div>
    <div class="head-container">
      <el-form ref="tableForm" :model="tableForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="模块名称" required>
              <el-input v-model="moduleName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="表名" required>
              <el-input v-model="tableName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="表单描述" required>
              <el-input v-model="formDesc" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <hr size="1" style='background-color:#e6e6ef6e; height:2px; border:none;margin-bottom: 10px;'/>
      <el-tabs v-model="activeName">

        <el-tab-pane label="数据库表设计" name="first">
          <div style="display:inline-block">
            <el-button v-show="existTable" style="margin-bottom: 10px" type="primary" icon="el-icon-plus" size="mini"
                       @click="openDialogFieldForm(false)"
            >新增列
            </el-button>

            <span style="margin-left: 220px;font-size: 14px;font-family: initial ">新建表名:</span>
            <el-input required="required" v-model="tableName" style="width: 200px;margin-right: 10px;"
                      placeholder="请输入表名">
              <template slot="append">必填</template>
            </el-input>
            <span style="font-size: 14px;font-family: initial">表描述:</span>
            <el-input required="required" style="width: 280px;" v-model="tableDesc" placeholder="请输入表描述">
              <template slot="append">必填</template>
            </el-input>
            <el-button v-show="!existTable" style="margin-bottom: 10px;margin-left: 10px" type="info"
                       icon="el-icon-refresh" size="mini"
                       @click="genDbTable"
            >生成表
            </el-button>
            <el-button v-show="existTable" style="margin-left: 10px" type="success" size="mini"
                       @click="editTableNameAndTableDesc">
              修改表名、表描述
            </el-button>
            <el-button v-show="existTable" style="margin-bottom: 10px" type="danger" icon="el-icon-remove-outline"
                       size="mini"
                       @click="deleteTable"
            >删除表
            </el-button>
          </div>
          <el-table
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column type="index" width="50"/>
            <el-table-column prop="columnName" label="列名"/>
            <el-table-column prop="columnDesc" label="列名描述"/>
            <el-table-column prop="dataType" label="数据类型"/>
            <el-table-column prop="columnLength" label="字段长度"/>
            <el-table-column prop="point" label="小数位数"/>
            <el-table-column prop="ifNull" label="是否为空" width="100"/>

            <el-table-column align="center" label="操作" width="160">
              <template slot-scope="scope">
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  size="mini"
                  @click="openDialogFieldForm(true,scope.row)"
                >修改
                </el-button>
                <el-button
                  style="margin-left: 10px"
                  type="danger"
                  size="mini"
                  @click="handleDeleteTableField(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 弹出框新增table -->
          <el-dialog title="业务字段" v-dialog-drag :visible.sync="dialogFieldFormVisible">
            <el-form
              ref="fieldForm"
              :model="fieldForm"
              :rules="rules"
              label-position="right"
              label-width="150px"
              style="width: 600px; margin-left:20px;"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="列名" prop="columnName">
                    <el-input v-model="fieldForm.columnName" maxlength="40"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="列名描述" label-width="100px" prop="columnDesc">
                    <el-input v-model="fieldForm.columnDesc" maxlength="30"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="数据类型" prop="dataType">
                    <el-select v-model="fieldForm.dataType" placeholder="请选择" style="width: 100%;"
                               @change="fieldTypeChange">
                      <el-option
                        v-for="item in selectList.fieldTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否允许为空" prop="ifNull">
                    <el-radio v-model="fieldForm.ifNull" label="notNull">notNull</el-radio>
                    <el-radio v-model="fieldForm.ifNull" label="null">null</el-radio>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="长度" prop="columnLength">
                    <el-input-number v-model="fieldForm.columnLength" :min="minNum" :max="maxNum" label="长度"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="小数位数" prop="point">
                    <el-input-number v-model="fieldForm.point" :min="0" :max="8" label="小数位数"/>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" plain @click="cancel">取 消</el-button>
              <el-button type="primary" @click="saveField">确 定</el-button>
            </div>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="页面属性" name="second">
          <el-form ref="tableForm" :model="tableForm" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="14">
                <el-tabs v-model="sqlActiveName">
                  <el-tab-pane label="查询" name="first">
                    <el-input type="textarea" class="sqlStyle" :autosize="{ minRows: 4, maxRows: 4}"
                              v-model="tableForm.selectSql"></el-input>
                  </el-tab-pane>
                  <el-tab-pane label="删除" name="second">
                    <el-input type="textarea" class="sqlStyle" :autosize="{ minRows: 4, maxRows: 4}"
                              v-model="tableForm.deleteSql"></el-input>
                  </el-tab-pane>
                  <el-tab-pane label="新增" name="four">
                    <el-input type="textarea" class="sqlStyle" :autosize="{ minRows: 4, maxRows: 4}"
                              v-model="tableForm.insertSql"></el-input>
                  </el-tab-pane>
                  <el-tab-pane label="修改" name="third">
                    <el-input type="textarea" class="sqlStyle" :autosize="{ minRows: 4, maxRows: 4}"
                              v-model="tableForm.updateSql"></el-input>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
              <el-col :span="10">
                <el-form-item label="查询参数:" style="margin-top: 53px;" v-show="sqlActiveName==='first'">
                  <el-input type="textarea" class="sqlStyle" :autosize="{ minRows: 4, maxRows: 8}"
                            v-model="tableForm.queryParams"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <hr size="1" style='background-color:#e6e6ef6e; height:2px; border:none;margin-bottom: 10px;'/>
            <el-table
              :data="tableData"
              border
              class="show_table"
            >
              <el-table-column prop="columnName" label="数据库字段" min-width="90"></el-table-column>
              <el-table-column prop="fieldCode" label="java字段" min-width="90"></el-table-column>
              <el-table-column prop="fieldDesc" label="字段描述" min-width="100"></el-table-column>
              <el-table-column prop="vueLabel" label="控件label值" min-width="100">
                <template slot-scope="scope">
                  <el-input size="small" v-model="scope.row.vueLabel"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="formShow" label="表单显示" width="50">
                <template slot-scope="scope">
                  <el-checkbox
                    :true-label="1"
                    :false-label="2"
                    v-model="scope.row.formShow">
                  </el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="listShow" label="列表显示" width="50">
                <template slot-scope="scope">
                  <el-checkbox
                    :true-label="1"
                    :false-label="2"
                    v-model="scope.row.listShow">
                  </el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="formSort" label="表单排序" width="70">
                <template slot-scope="scope">
                  <el-input size="small" v-model.number="scope.row.formSort"
                            oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="listSort" label="列表排序" width="70">
                <template slot-scope="scope">
                  <el-input size="small" v-model.number="scope.row.listSort"
                            oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="vueType" label="控件类型" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.vueType" filterable allow-create>
                    <el-option v-for="item in selectList.vueTypeList " :key="item.value" :label="item.label"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="vueLength" label="控件长度" width="140">
                <template slot-scope="scope">
                  <el-input size="small" v-model.number="scope.row.vueLength"
                            oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="isQuery" label="是否查询" width="50">
                <template slot-scope="scope">
                  <el-checkbox
                    :true-label="1"
                    :false-label="2"
                    v-model="scope.row.isQuery">
                  </el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="queryType" label="查询类型" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.queryType" filterable allow-create>
                    <el-option v-for="item in selectList.queryTypeList " :key="item.value" :label="item.label"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="vueFormat" label="自定义格式化" min-width="300">
                <template slot-scope="scope">
                  <el-input size="small" v-model="scope.row.vueFormat"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <hr size="1" style='background-color:#e6e6ef6e; height:2px; border:none;margin-bottom: 10px;'/>
          </el-form>
          <div class="dialog-footer" style="float: left;">
            <el-button type="primary" @click="genFormData" style="margin-right: 20px">更新表格数据</el-button>
            <el-button type="warning" @click="openFormDesign" style="width:120px;">表单设计</el-button>
          </div>
          <div class="dialog-footer" style="float: right;">
            <el-button type="primary" style="margin-right: 50px" :loading="crudSqlLoading" @click="updateCrudSql">
              更新CRUD_Sql
            </el-button>
            <el-button type="primary" plain style="margin-right: 10px" @click="close">关 闭</el-button>
            <el-button type="primary" @click="saveTable(true)">保 存</el-button>
          </div>
        </el-tab-pane>

      </el-tabs>
    </div>
  </div>
</template>

<script>
  import {
    add,
    edit,
    del,
    genFormData,
    doCrud,
    addFormAndFormField,
    editFormAndFormField,
    loadModuleData,
    getTablePage
  } from '@/api/system/moduleformfield'
  import tableField from '@/api/system/modeltablefield.js'
  import msgUtil from '@/utils/msgUtil'

  import design from '../design'
  // 定义页面属性 的表单
  const tableForm = {
    id: '',
    insertSql: '',
    deleteSql: '',
    updateSql: '',
    selectSql: '',
    queryParams: '',
  }
  // 定义表设计 的表单
  const fieldForm = {
    id: null,
    tableName: '',
    tableDesc: '',
    columnName: '',
    columnDesc: '',
    dataType: 'varchar',
    ifNull: 'null',
    columnLength: 32,
    point: 0,
  }
  export default {
    components: { design},
    data() {
      return {
        existTable: false,
        minNum: 0,
        maxNum: 4000,
        fieldForm: fieldForm,
        dialogFieldFormVisible: false,
        editorVisible: false,
        crudSqlLoading: false,
        tableData: [],
        moduleFormId: this.$route.query.moduleFormId,
        moduleName: '',
        tableName: '',
        formDesc: '',
        tableDesc: '',
        dialogTitle: '',
        formJson: '',
        activeName: 'first',
        sqlActiveName: 'first',
        isEdit: false,
        tableForm: tableForm,
        dialogTableFormVisible: false, // 弹出的新增修改表单窗口
        selTableId: 0, // 选中行的tableId
        selType: 0, // 选中的创建文件类型
        tableKey: 0,
        list: null,
        listLoading: false,
        total: 0,
        selectList: {
          //控件类型列表
          vueTypeList: [{label: '文本框', value: '文本框'}, {label: '下拉框(单选)', value: '下拉框(单选)'}, {
            label: '下拉框字典(单选)',
            value: '下拉框字典(单选)'
          }, {label: '下拉框(多选)', value: '下拉框(多选)'}, {label: '下拉框字典(多选)', value: '下拉框字典(多选)'},
            {label: '单选框', value: '单选框'}, {label: '复选框', value: '复选框'}, {
              label: '多行文本框',
              value: '多行文本框'
            }, {label: '日期(年月日)', value: '日期(年月日)'}, {label: '日期(年月日时分秒)', value: '日期(年月日时分秒)'},
            {label: '日期(年)', value: '日期(年)'}, {label: '日期(年月)', value: '日期(年月)'},],
          queryTypeList: [{label: '等于(=)', value: '等于(=)'}, {label: '大于(>)', value: '大于(>)'}, {
            label: '大于等于(>=)',
            value: '大于等于(>=)'
          }, {label: '小于(<)', value: '小于(<)'},
            {label: '小于等于(<=)', value: '小于等于(<=)'}, {label: '模糊查询(like)', value: '模糊查询(like)'}, {
              label: '范围查询(in)',
              value: '范围查询(in)'
            },],
          fieldTypeList: [{label: 'varchar', value: 'varchar'}, {label: 'int', value: 'int'}, {
            label: 'double',
            value: 'double'
          }, {label: 'datetime', value: 'datetime'}, {label: 'long', value: 'long'}, {label: 'text', value: 'text'}]
        },
        listQuery: {
          pageNo: 0,
          pageSize: 10,
          condition: '',
          moduleFormId: this.$route.query.moduleFormId,
        },
        rules: {
          tableName: [{required: true, trigger: 'blur', message: '数据表名不能为空'}],
          tableNameDesc: [{required: true, trigger: 'blur', message: '数据表名描述不能为空'}],
          dataType: [{required: true, trigger: 'blur', message: '字段类型不能为空'}],
          columnLength: [{required: true, trigger: 'blur', message: '字段长度不能为空'}],
          ifNull: [{required: true, trigger: 'blur', message: '请选择是否为空'}]
        }
      }
    },
    created() {
      this.getTablePage()
    },
    methods: {
      deleteTable() {
        msgUtil.confirm('确认删除表及字段数据?').then(async () => {
          tableField.deleteTable(this.moduleFormId).then(res => {
            msgUtil.success2("表删除成功!")
            this.getTablePage()
          })
        })
      },
      genDbTable() {
        let params = {
          moduleFormId: this.moduleFormId,
          tableName: this.tableName,
          tableDesc: this.tableDesc
        }
        tableField.genDbTable(params).then(res => {
          msgUtil.success2("表创建成功!")
          this.getTablePage()
        })
      },
      editTableNameAndTableDesc() {
        let params = {
          moduleFormId: this.moduleFormId,
          tableName: this.tableName,
          tableDesc: this.tableDesc
        }
        tableField.editTableNameAndTableDesc(params).then(res => {
          msgUtil.success2("表名及备注修改成功!")
          this.getTablePage()
        })
      },
      saveField() {
        if (this.isEdit) {
          tableField.edit(this.fieldForm).then(res => {
            this.getFieldPage()
            this.dialogFieldFormVisible = false
            msgUtil.success2('列修改成功')
          })
        } else {
          let params = this.fieldForm
          params.tableName = this.tableName
          params.tableDesc = this.tableDesc
          params.moduleFormId = this.moduleFormId
          tableField.add(params).then(res => {
            msgUtil.success2('列新增成功')
            this.getFieldPage()
          })
        }
      },
      getFieldPage() {
        this.listLoading = true
        let params = {...this.listQuery}
        params.tableName = this.tableName
        tableField.getTablePage(params).then(res => {
          this.list = res.data.content
          this.total = res.data.totalElements
          res.data.content.forEach((item, index) => {
            item.listIndex = index
          });
          this.$nextTick(() => {
            this.listLoading = false
          })
        })
      },
      fieldTypeChange(fieldType) {
        if (fieldType === 'varchar') {
          this.fieldForm.columnLength = 32
          this.fieldForm.point = 0
          this.minNum = 2
          this.maxNum = 4000
        } else if (fieldType === 'int') {
          this.fieldForm.columnLength = 11
          this.fieldForm.point = 0
          this.minNum = 1
          this.maxNum = 11
        } else if (fieldType === 'datetime') {
          this.fieldForm.columnLength = 0
          this.fieldForm.point = 0
          this.minNum = 0
          this.maxNum = 0
        } else if (fieldType === 'long') {
          this.fieldForm.columnLength = 11
          this.fieldForm.point = 0
          this.minNum = 1
          this.maxNum = 16
        } else if (fieldType === 'double') {
          this.fieldForm.columnLength = 11
          this.fieldForm.point = 2
          this.minNum = 1
          this.maxNum = 11
        } else if (fieldType === 'text') {
          this.fieldForm.columnLength = 0
          this.fieldForm.point = 0
          this.minNum = 0
          this.maxNum = 0
        } else {
          this.fieldForm.columnLength = 32
          this.fieldForm.point = 0
          this.minNum = 2
          this.maxNum = 4000
        }
      },
      // 打开fieldform窗口
      openDialogFieldForm(isEdit, row) {
        this.isEdit = isEdit
        if (isEdit) {
          this.fieldForm = {...row}
          this.dialogFieldFormVisible = true
        } else {
          this.fieldForm = {
            id: null,
            tableName: '',
            tableDesc: '',
            columnName: '',
            columnDesc: '',
            dataType: 'varchar',
            ifNull: 'null',
            columnLength: 32,
            point: 0,
          }
          this.dialogFieldFormVisible = true
        }
      },
      closeAndSave(done) {
        msgUtil.confirm2('是否保存修改?', '保存并退出', '直接退出').then(async () => {
          this.$refs.designData.getContainerData()
          this.getTablePage()
          done()
        }).catch(action => {
          done()
        });
      },
      genCrudSql() {
        let insertColumns = ''
        let insertFields = ''
        let updateCode = ''
        let selectCode = ''
        let queryParams = ''
        this.tableData.forEach(item => {
          let strCheck = ''
          let queryLogic = '='
          let queryLikeRight = ''
          if (item.isQuery == 1) {
            queryParams += item.fieldCode + ','
            if (item.vueType === '文本框') {
              strCheck = 'and ' + item.fieldCode + '!=\'\''
            }
            if (item.queryType === '等于(=)') {
              queryLogic = ' ='
            } else if (item.queryType === '大于(>)') {
              queryLogic = ' &gt;'
            } else if (item.queryType === '大于等于(>=)') {
              queryLogic = ' &gt;='
            } else if (item.queryType === '小于(<)') {
              queryLogic = ' &lt;'
            } else if (item.queryType === '小于等于(<=)') {
              queryLogic = ' &lt;='
            } else if (item.queryType === '模糊查询(like)') {
              queryLogic = ' like concat(\'%\','
              queryLikeRight = ',\'%\')'
            }
            selectCode += '<if test="' + item.fieldCode + ' != null ' + strCheck + ' "> and ' + item.columnName + queryLogic + '#{' + item.fieldCode + '}' + queryLikeRight + '</if>'
          }
          if (item.fieldCode === 'createrName' || item.fieldCode === 'createTimeFrom' || item.fieldCode === 'createTimeTo' || item.fieldCode === 'createrId' || item.fieldCode === 'createTime') return
          insertColumns += item.columnName + ','
          insertFields += '#{' + item.fieldCode + '},'
          updateCode += '<if test="' + item.fieldCode + ' != null">' + item.columnName + ' =#{' + item.fieldCode + '},</if>'
        })

        insertColumns = insertColumns.substring(0, insertColumns.length - 1)
        insertFields = insertFields.substring(0, insertFields.length - 1)
        let loginUserCom = JSON.parse(localStorage.getItem('sysCompany'))
        let tableName = loginUserCom.code + '_' + this.tableName
        this.tableForm.insertSql = 'insert into ' + tableName + '(id,creater_id,create_time,updater_id,update_time,creater_com_id,' + insertColumns + ')values(#{id},#{createrId},' +
          '#{createTime},#{updaterId},#{updateTime},#{createrComId},' + insertFields + ')'
        this.tableForm.deleteSql = 'delete from ' + tableName + ' where id =#{id}'
        this.tableForm.updateSql = 'update ' + tableName + ' <set> <if test="updaterId != null">updater_id=#{updaterId},</if><if test="updateTime != null">update_time=#{updateTime},</if>' +
          '<if test="version != null">version=#{version},</if>' + updateCode + '</set> where id=#{id}'
        this.tableForm.selectSql = '<script' + '>' +
          'select * from ' + tableName + ' <where>' + selectCode + '</where> order by update_time desc<' + '/script>'
        queryParams = queryParams.substring(0, queryParams.length - 1)
        this.tableForm.queryParams = queryParams
        this.tableForm.moduleFormId = this.moduleFormId
      },
      updateCrudSql() {
        this.crudSqlLoading = true
        setTimeout(() => {
          msgUtil.success2('更新成功!')
          this.crudSqlLoading = false
          this.genCrudSql()
        }, 300)
      },
      //拆分数组
      groupArr(sourceArr, newArrLength) {
        let index = 0;
        let newArray = [];
        while (index < sourceArr.length) {
          newArray.push(sourceArr.slice(index, index += newArrLength));
        }
        return newArray;
      },
      openFormDesign() {
        this.saveTable(false)
        this.editorVisible = true
        if (this.formJson === '' || this.formJson === null || this.formJson.list.length === 0) {
          let list = []
          let json = {
            list: list,
            config: {
              labelWidth: 100,
              labelPosition: 'right',
              size: 'small',
              customClass: ''

            }
          }
          let formList = []
          this.tableData.forEach(item => {
            if (item.formShow == 1) {
              formList.push(item)
            }
          })
          //排序
          formList.sort(function (a, b) {
            return a.formSort - b.formSort
          })
          //先拆分成2个一组
          let groupArrs = this.groupArr(formList, 2)
          groupArrs.forEach((arr, index) => {
            let obj = {
              type: 'grid',
              icon: 'icon-grid-',
              columns: [],
              options: {
                gutter: 0,
                justify: 'start',
                align: 'top',
                remoteFunc: 'func_' + index
              },
              name: '栅格布局',
              key: index.toString(),
              model: 'grid_' + index,
              rules: []
            }
            arr.forEach(item => {
              let list2 = []
              let obj3 = this.formType(item)
              list2.push(obj3)
              let obj2 = {
                span: 12,
                list: list2
              }
              obj.columns.push(obj2)
            })
            list.push(obj)
          })
          this.formJson = json
        }
      },
      genFormData() {
        if (this.tableData.length !== 0) {
          msgUtil.confirm('页面数据已存在是否初始化?').then(async () => {
            this.genFormData2()
          })
        } else {
          this.genFormData2()
        }
        this.isEdit = false
      },
      genFormData2() {
        let param = {
          moduleFormId: this.moduleFormId,
          tableName: this.tableName
        }
        genFormData(param).then(response => {
          msgUtil.success2('数据生成成功')
          this.tableData = response.data
          this.genCrudSql()
        })
      },
      close() {
        this.cancel()
        this.$router.push({
          path: '/module',
        })
      },
      cancel() {
        this.dialogFieldFormVisible = false
        this.tableForm = {
          id: '',
          insertSql: '',
          deleteSql: '',
          updateSql: '',
          selectSql: '',
          queryParams: ''
        }
        this.fieldForm = {
          id: null,
          tableName: '',
          tableDesc: '',
          columnName: '',
          columnDesc: '',
          dataType: 'varchar',
          ifNull: 'null',
          columnLength: 32,
          point: 0,
        }
        this.minNum = 0,
          this.maxNum = 4000
      },
      // 保存数据表配置
      saveTable(showTitle) {
        this.$refs.tableForm.validate(valid => {
          if (valid) {
            this.genCrudSql()
            let params = []
            this.tableData.forEach((item, index) => {
              let param = {}
              if (index == 0) param = {...this.tableForm}
              for (let key in  item) {
                param[key] = item[key]
              }
              param.moduleFormId = this.moduleFormId
              params.push(param)
            })
            if (this.isEdit) {
              editFormAndFormField(params).then(response => {
                if (showTitle) {
                  msgUtil.success2('数据表修改成功')
                }
                this.getTablePage()
              })
            } else {
              addFormAndFormField(params).then(response => {
                if (showTitle) {
                  msgUtil.success2('数据表添加成功')
                }
                this.getTablePage()
              })
            }
          }
        })
      },

      getTablePage() {
        this.cancel()
        this.listLoading = true
        if (this.listQuery.moduleFormId === undefined) return
        loadModuleData(this.listQuery.moduleFormId).then(res => {
          this.tableName = res.data.tableName
          this.existTable = this.tableName === '' ? false : true
          this.tableDesc = res.data.tableDesc
          this.formDesc = res.data.formDesc
          this.moduleName = res.data.moduleName
          this.dialogTitle = res.data.formDesc + '(Esc退出)'
          this.tableData = res.data.moduleFormFieldList
          if (this.tableName !== '' && this.tableData.length > 0) {
            this.activeName = 'second'
          }
          this.formJson = JSON.parse(res.data.formJson)
          if (this.tableData.length !== 0) {
            this.tableForm.selectSql = res.data.selectSql
            this.tableForm.updateSql = res.data.updateSql
            this.tableForm.deleteSql = res.data.deleteSql
            this.tableForm.insertSql = res.data.insertSql
            this.tableForm.queryParams = res.data.queryParams
            this.isEdit = true
          }
          this.getFieldPage()
          this.$nextTick(() => {
            this.listLoading = false
          })
        })
      },
      handleSelectionChange(val) {
        if (val.length > 1) {
          this.$refs.genTable.clearSelection()
          this.$refs.genTable.toggleRowSelection(val[val.length - 1])
        } else if (val.length === 0) {
          this.selTableId = 0
        } else {
          this.multipleSelection = val[val.length - 1]
          this.selTableId = val[0].id
        }
      },
      // 打开tableform窗口
      openDialogTableForm(isEdit, row) {
        this.isEdit = isEdit
        if (isEdit) {
          this.tableForm = row
          this.dialogTableFormVisible = true
        } else {
          this.dialogTableFormVisible = true
          this.tableForm = {
            id: '',
            tableName: '',
            tableNameDesc: '',
            modelName: '',
            authorName: '',
            javaPackage: ''
          }
        }
      },
      formType(column) {

        let obj = {}
        if (column.vueType === '文本框') {
          obj = {
            type: 'input',
            icon: 'icon-input',
            options: {
              width: '70%',
              defaultValue: '',
              required: false,
              dataType: 'string',
              pattern: '',
              placeholder: column.fieldDesc,
              disabled: false,
              remoteFunc: 'func_' + column.fieldCode
            },
            name: column.fieldDesc,
            key: column.fieldCode,
            model: column.fieldCode,
            rules: [{
              required: false,
              message: column.fieldDesc + '不能为空'
            }]
          }
          return obj;
        } else if (column.vueType.indexOf('下拉框') != -1) {
          obj = {
            type: 'select',
            icon: 'icon-select',
            options: {
              defaultValue: '',
              multiple: false,
              clearable: true,
              required: false,
              disabled: false,
              showLabel: false,
              width: '70%',
              options: [],
              remote: true,
              filterable: true,
              remoteOptions: [],
              props: {
                value: 'value',
                label: 'label'
              },
              remoteFunc: 'func_' + column.fieldCode,
            },
            name: column.fieldDesc,
            key: column.fieldCode,
            model: column.fieldCode,
            rules: []
          }
        } else if (column.vueType.indexOf('日期') != -1) {
          obj = {
            type: 'date',
            icon: 'icon-date',
            options: {
              readonly: false,
              disabled: false,
              editable: true,
              clearable: true,
              placeholder: column.fieldDesc,
              startPlaceholder: '',
              endPlaceholder: '',
              type: 'date',
              format: 'yyyy-MM-dd',
              timestamp: false,
              required: false,
              width: '70%',
              remoteFunc: 'func_' + column.fieldCode,
            },
            name: column.fieldDesc,
            key: column.fieldCode,
            model: column.fieldCode,
            rules: []
          }
        }
        return obj;
      },
      // 删除
      handleDelete(row) {
        msgUtil.confirm('确认删除表数据?').then(async () => {
          const ids = []
          ids.push(row.id)
          await del(ids)
          msgUtil.success2('删除成功!')
          this.getTablePage()
        })
      },
      // 删除表字段
      handleDeleteTableField(row) {
        msgUtil.confirm('确认删除表数据?').then(async () => {
          const ids = []
          ids.push(row.id)
          await tableField.del(ids)
          msgUtil.success2('删除成功!')
          this.getTablePage()
        })
      },
    }
  }
</script>
<style lang="scss">
  .el-dialog {
    border-radius: 15px;
  }

  .sqlStyle .el-textarea__inner {
    min-height: 88px;
    height: 88px;
    color: #4072ff !important;
    font-family: monospace !important;
  }

  .fieldIndex .el-dialog__title {
    font-family: monospace;
  }
</style>
<style scoped lang="scss">
  .show_table {
    position: relative;
    width: 100%;
    height: 402px;
    overflow: auto;
  }

  .saveFormJson {
    float: right;
    margin-top: -50px;
    margin-right: 50px;
    font-size: 12px;
    width: 90px
  }

</style>
